<?php
/**
 * @package		yos_news_crawler
 * @subpackage	Helper
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

/**
 * YOS Find and Replace
 */
class YOS_Find_Replace extends JObject 
{	
	/**
	 * Find and replace
	 * example /<div>abc (.*?) def (.*?) ghi<\/div>/ism<=>this $1 and $2 finish
	 *
	 * @param string $str_in
	 * @param array $arr_regex
	 */
	function find_replace($str_in, $arr_regex){
		$str_out = $str_in;
		for ($k	= 0; $k < count($arr_regex); $k++){
			$arr_find_replace = explode('<=>', $arr_regex[$k]);
			if (count($arr_find_replace) != 2) {
				continue;
			}
			
			$str_find_regex = $arr_find_replace[0];
			$str_replace = $arr_find_replace[1];
			if (!@preg_match_all($str_find_regex, $str_out, $matches)) {
				continue;
			}
			
			//encode
			for ($i = 0; $i < count($matches[0]); $i++){
				$str_out = str_replace($matches[0][$i], 'YOS_KEY_'.sprintf('%06d',$i), $str_out);
			}
			
			for ($i = 0; $i < count($matches[0]); $i++){
				//build repplace string
				$str_replace2 = $str_replace;
				for($j = 0; $j < count($matches); $j++){
					$str_replace2 = str_replace('$'.$j, $matches[$j][$i], $str_replace2);
				}
				$matches[0][$i] = $str_replace2;								
			}
			
			//replace (decode)
			for ($i = 0; $i < count($matches[0]); $i++){
				$str_out = str_replace('YOS_KEY_'.sprintf('%06d',$i), $matches[0][$i], $str_out);
			}
		}
		
		return $str_out;
	}
}